#pragma once

#include <iostream>
#include <fstream>
#include <vector>
#include <mutex>
#include <cassert>
#include <algorithm>
#include <jsoncpp/json/json.h>

#include "../common/log.hpp"
#include "../common/util.hpp"
#include "../common/httplib.h"
#include "oj_mysql_model.hpp"
// #include "oj_model.hpp"
#include "oj_view.hpp"

namespace rs_control
{
    using namespace rs_log;
    using namespace rs_util;
    using namespace rs_view;
    using namespace rs_model;
    using namespace httplib;

    class Machine
    {
    public:
        std::string ip;//主机ip地址
        int port;//主机端口号
        uint64_t load;//负载个数
        std::mutex *mtx;

    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

    public:
        //增加负载
        void InLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        //减少负载
        void DeLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }
        //获取负载
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }
    };

    const std::string server_machine_path = "./conf/server_machine.conf";
    //负载均衡模块
    class LoadBlance
    {
    private:
        std::vector<Machine> machines;//
        std::vector<int> online;//在线主机
        std::vector<int> offline;//下线主机
        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(server_machine_path));
            std::cout << "加载" << server_machine_path << "成功" << std::endl;
        }
        ~LoadBlance()
        {
        }

    public:
        //加载主机列表
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_conf << "失败" << std::endl;
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tmp;
                StringUtil::SplitString(line,&tmp,":");

                if (tmp.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败" << std::endl;
                    return false;
                }

                Machine m;
                m.ip = tmp[0];
                m.port = atoi(tmp[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex;
                
                online.push_back(machines.size());
                machines.push_back(m);
            }
            in.close();
            return true;
        }
        //智能选择负载少的主机
        bool SmartChoice(int *id, Machine **m)
        {
            mtx.lock();

            int online_num = online.size();
            std::cout << online_num << endl;
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(ERROR) << "后台主机已经全部离线" << std::endl;
                return false;
            }

            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = (*m)->Load();
            for(int i = 1;i < online.size();i++)
            {
                uint64_t cur_load = machines[online[i]].Load();
                if(min_load > cur_load)
                {
                    min_load = cur_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }

            mtx.unlock();
            return true;
        }

        void OnAllMachine()
        {
            
            mtx.lock();
            
            online.insert(online.end(),offline.begin(),offline.end());
            offline.erase(offline.begin(),offline.end());
            

            
            mtx.unlock();
            LOG(INFO)<<"已经上线所有主机"<<endl;
        }

        void OffMachine(int id)
        {
            mtx.lock();
            for(auto iter = online.begin();iter != online.end();iter++)
            {
                if(*iter == id)
                {
                    machines[id].ResetLoad();
                    online.erase(iter);
                    offline.push_back(id);
                    break;
                }
            }
            
            mtx.unlock();
        }
        //查询主机在线情况
        void ShowMatchine()
        {
            mtx.lock();
            std::cout << "当前在线主机id列表：";
            for(auto& id:online)
            {
                std::cout << (id) <<' ';

            }
            std::cout << std::endl;

            std::cout << "当前离线主机id列表：";
            for(auto& id:offline)
            {
                std::cout << (id) <<' ';

            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model _model;
        LoadBlance _loadblance;
        View _view;
    public:
        Control()
        {}
        ~Control()
        {}
    public:
        void RecoverrAll()
        {
            _loadblance.OnAllMachine();
        }
        //形成所有题目到网页
        bool AllQuestions(std::string*html)
        {
            bool ret = true;
            vector<struct rs_model::Question> all;
            if(_model.GetAllQuestion(&all))
            {
                std::sort(all.begin(),all.end(),[](const Question& q1,const Question& q2)
                {
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                //将题目渲染到网页
                _view.AllExpandHtml(all,html);
            }
            else
            {
                LOG(ERROR) << "获取所有题目形成网页失败" << std::endl;
                ret = false;
            }

            return ret;
        }

        bool OneQuestion(const std::string&number,std::string*html)
        {
            bool ret = true;
            struct rs_model::Question theone;
            if(_model.GetOneQuestion(number,&theone))
            {
                std::cout << theone.title << std::endl;
                _view.OneExpandHtml(theone,html);
            }
            else
            {
                LOG(ERROR) << "获取指定题目形成网页失败" << std::endl;
                ret = false;
            }

            return ret;
        }

        void Judge(const std::string& number,const std::string in_json,std::string *out_json)
        {
            std::cout << "in_json" << "\nnumber:"<<number<<std::endl;
            struct Question q;
            _model.GetOneQuestion(number,&q);

            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json,in_value);
            std::string code = in_value["code"].asString();

            Json::Value complie_value;
            complie_value["input"] = in_value["input"].asString();
            complie_value["code"] = code + q.tail;
            complie_value["cpu_limit"] = q.cpu_limit;
            complie_value["mem_limit"] = q.mem_limit;

            Json::FastWriter writer;
            std::string complie_string = writer.write(complie_value);

            while(true)
            {
                int id = 0;
                Machine *m = nullptr;
                if(!_loadblance.SmartChoice(&id,&m))
                {
                    break;
                }

                LOG(INFO) << "选择主机:"  << id <<" "<< m->ip <<":"<< m->port <<"主机负载为："<<m->Load()<<endl;

                Client cli(m->ip,m->port);

                m->InLoad();

                if(auto res = cli.Post("/complier_and_run",complie_string,"application/jsoncpp;charset=utf-8"))
                {
                    if(res->status == 200)
                    {
                        (*out_json) = res->body;
                        m->DeLoad();
                        LOG(INFO)<<"请求编译和运行成功"<<endl;
                        break;
                    }
                    m->DeLoad();
                    
                } 
                else
                {
                    LOG(ERROR) << "加载主机情况失败：" << id <<" "<< m->ip <<":"<< m->port <<"可能离线"<<endl;
                    _loadblance.OffMachine(id);
                    
                    
                }  
            }
            _loadblance.ShowMatchine();

        }



    };
}